package com.envper.common.service.cls.impl;

import com.envper.common.domain.dto.ClassMemberDto;
import com.envper.common.exception.GlobalException;
import com.envper.common.mapper.ClassMapper;
import com.envper.common.service.cls.ClassMemberService;
import com.envper.common.util.IdUtils;
import com.envper.mysql.base.service.ClassMemberBaseService;
import com.envper.mysql.domain.Status;
import com.envper.mysql.domain.entity.TClassMember;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ClassMemberServiceImpl implements ClassMemberService {
    private final ClassMemberBaseService classMemberBaseService;

    @Override
    public List<ClassMemberDto> getClassMemberList() {
        List<TClassMember> tClassMemberList = classMemberBaseService.list();
        return ClassMapper.INSTANCE.toClassMemberDtoList(tClassMemberList);
    }

    @Override
    public List<ClassMemberDto> getClassMemberList(String id) {
        List<TClassMember> tClassMemberList = classMemberBaseService.list(new QueryWrapper().eq("class_id", id));
        return ClassMapper.INSTANCE.toClassMemberDtoList(tClassMemberList);
    }

    @Override
    public void addClassMember(ClassMemberDto classMemberDto) {
        TClassMember tClassMember = TClassMember.builder()
                .id(IdUtils.createId())
                .classId(classMemberDto.getClassId())
                .userId(classMemberDto.getUserId())
                .joined(LocalDateTime.now())
                .build();
        boolean save = classMemberBaseService.save(tClassMember);
        if (!save) {
            throw new GlobalException(Status.SAVEERROR);
        }
    }

    @Override
    public void addClassMember(Long classId, Long userId) {
        addClassMember(ClassMemberDto.builder()
                .classId(classId)
                .userId(userId)
                .build());
    }
}
